package com.sinochem.yunlian.ship.common.filter;

import java.util.HashMap;
import javax.servlet.http.HttpServletRequest;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import com.alibaba.fastjson.JSONObject;
import com.sinochem.yunlian.ship.common.tuple.BodyPair;

/**
 * 解析Body参数
 */
@Component
@Aspect
public class RequestBodysFilter {
	
	private static final Logger logger =  LoggerFactory.getLogger(RequestBodysFilter.class);
	
	@Pointcut("@annotation(com.sinochem.yunlian.ship.common.annotation.RequestBodys)")
	private void aspect(){}

	@Around("aspect()")
    public Object excGetBody(ProceedingJoinPoint joinPoint) throws Throwable {
		
		
		Object[] objects = null;

		HashMap<Object, Object> hashMap = new HashMap<>();
		
		// 获取参数对象
		objects = joinPoint.getArgs();
		
		if (objects !=null  && objects.length > 0) {
			getObject(objects, hashMap);
		} 
		logger.info("解析后的参数列表:{}", objects);
		return joinPoint.proceed(objects);
    }
	
	/**
	 * 
	 * @param objects
	 * @param hashMap
	 * 
	 * @Author WJS
	 */
	private void getObject(Object[] objects, HashMap<Object, Object> hashMap) {
		
		ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
		HttpServletRequest request = attributes.getRequest();
		
		logger.info("请求方式:{}",request.getMethod());
		
		switch (request.getMethod()) {
		
		case "GET":
			
			logger.info("不支持GET请求....");

			break;
			
		case "POST":
			initParameterObject(objects, hashMap);
			break;
		default:
			
			break;
		}

	}
	/**
	 * 
	 * @param objects
	 * @param hashMap
	 * 
	 * @Author WJS
	 */
	private void initParameterObject(Object[] objects, HashMap<Object, Object> hashMap) {
		
		BodyPair body = null;
		
		for (Object object : objects) {
			
			if (object instanceof BodyPair) {
				
				body = (BodyPair) object;
				break;
			} 
		}
		logger.info("输出body内容:{}", body);
		
		if (body != null) {
			
			for (int i = 0; i < objects.length; i++) {
				
				if (!(objects[i] instanceof BodyPair)) {
					
					Object objectValue = body.getBody(objects[i].getClass().getSimpleName());
					
					if (objectValue != null) {
						objects[i] = JSONObject.parseObject(objectValue + "", objects[i].getClass());
						//objects[i] = JSONObject.parseObject(JSONObject.toJSONString(objectValue), objects[i].getClass());
					} else {
						objects[i] = null;
					}
					logger.info("输出初始化的请求对象:{}", objects[i]);
				} 
			}
		}
		
	}

}
